//
//  HMProposalAll.swift
//  HealthMonitoring
//
//  Created by 珠海正杰 on 2018/9/3.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

import UIKit
import SwiftyJSON

/// 每个选项的 内容
class HMProposalAll: HMViewController {
    
    var cellHeight: CGFloat = 0
    var titleSign: String = ""
    
//    var isRemindType = ""
    var  dataJson =  JSON()//Array<Any>()
     lazy var table: UITableView = {
       let _table = UITableView()
        return _table
    }()
    
    
    private lazy var subViewNullData: UIView = {
        return UIView.creatoreBgNullDataView(frame: CGRect.zero)
    }()
    
    
    override func setupView() {
         view.backgroundColor = UIColor.white
      
        if self.titleSign == "用药建议" {
          view.addSubview(subViewNullData) // 没有数据时显示
        }else {
           self.setNavRightView()
        }
        view.addSubview(table)

        if self.titleSign == "用药建议" {
          subViewNullData.isHidden = false
          subViewNullData.leadingAlign(view:  view, predicate: "0")
          subViewNullData.trailingAlign(view: view, predicate: "0")
          subViewNullData.height(view: table)
          table.isHidden = true  //先隐藏
        }
            
        table.delegate = self
        table.dataSource = self
        table.register(HMProposalCell.self, forCellReuseIdentifier: "cell")
        table.register(HMFoundProposalCell.self, forCellReuseIdentifier: "HMFoundProposalCell")
        table.topAlign(view: view, predicate: "0")
        table.leadingAlign(view: view, predicate: "0")
        table.width(view: view)
        table.bottomAlign(view: view, predicate: "-44")
        
        
        self.updateTable(type: self._signStr)
        
    }
    

    func updateTable(type: String) {
        NetRequestTool.shareInstance.met = .get
        if self.titleSign == "用药建议" {
            //
            NetRequestTool.request(url: "user/medicine/suggestion-brief", parameters: ["type": type], success: { (json) in

                if json["data"].count != 0 {
                    self.subViewNullData.isHidden = true
                    self.table.isHidden = false

                }else {
                    self.subViewNullData.isHidden = false
                    self.table.isHidden = true

                }

                self.dataJson = json["data"]
                self.table.reloadData()

            }, fail: { (code, err) in

            }) {

            }
        }else {
            
            // 医生获取处方列表
            NetRequestTool.request(url: "doctor/doc/presc-list", parameters: [:], success: { (json) in
                self.table.isHidden = false
                self.dataJson = json["data"]
                self.table.reloadData()
                
            }, fail: { (code, err) in
                
            }) {
                
            }
        }
        
    
        
        
    }
    
    // 设置创建按钮
    func setNavRightView()  {
        let setBtn =  UIButton(frame: CGRect(x: 0, y: 0, width: 24, height: 24))
        setBtn.setImage(UIImage.init(named: "add"), for: UIControlState.normal)
        setBtn.setTitleColor(configure.shareConfigure.HMColor1, for: .normal)
        let rightBtn = UIBarButtonItem(customView: setBtn)
        setBtn.addTarget(self, action: #selector(navRightBtn), for: UIControlEvents.touchUpInside)
        let negativeSpacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        negativeSpacer.width = -10
        
        navigationItem.rightBarButtonItems = [negativeSpacer, rightBtn]
    }
    @objc func navRightBtn(sender: UIButton) {
        // 表示从医生出诊
        if self.titleSign == "医生出诊" {
            let matter = HMRemindMatter()
            matter.inletName = "医生出诊"
            //            matter.isReturnType = "data"   //self.isRemindType
            self.pushViewController(matter)
            
        }
        
        
    }
    
}

extension HMProposalAll: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
//        if self.titleSign == "用药建议" {
            return 1
//        }else {
//            return 2
//        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return self.dataJson.count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
//        if self.titleSign != "用药建议" {
//            return 80
//        }else {
            return 0
//        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//        if self.titleSign == "用药建议" {
            return nil
//        }else {
//            let subView = UIView.init(frame: CGRect.init(x: 0, y: 0, width:tableView.frame.size.width, height: 80))
//            subView.addTapGesture(target: self, action: #selector(subviewClick(sender:)))
//
//            let addIcon = UIImageView()
//            let text = UILabel()
//            subView.addSubview(addIcon)
//            subView.addSubview(text)
//
//            addIcon.image = UIImage.init(named: "add")
//            text.text = "添加新档案"
//            text.textColor = configure.shareConfigure.HMColor4
//            addIcon.centerXAlign(view: subView, predicate: "0")
//            addIcon.centerYAlign(view: subView, predicate: "-10")
//            addIcon.widthConstrain(predicate: "35")
//            addIcon.heightConstrain(predicate: "35")
//            text.topVertically(view: addIcon)
//            text.centerXAlign(view: subView)
//
//            return subView
//        }
        
    }
    
   
    
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
          return self.cellHeight
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
          return self.cellStyle(tableView, cellForRowAt: indexPath)
    }
    
    func cellStyle(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
    
        let data = (self.dataJson[indexPath.row].dictionary)!
        var dateStr = String.chineseTime(frome: (data["lastModifiedDate"]?.stringValue)!)
        dateStr = String(dateStr.prefix(dateStr.count - 3))
        
        // 生活建议部分
        var adviseAry = Array<String>()
        adviseAry.append(data["remark"]!.stringValue)
        let arry =  ["title": "生活建议:", "ary": adviseAry] as [String : Any]
        
        //药单部分
        var drugsAry  = (data["medicines"]?.array)!
        drugsAry.insert(["medicineName": "药名", "treatment": "疗程"], at: 0)
        
        
        var moreName = ""
        var btnName = ""
         if self.titleSign == "用药建议" {
            btnName = "添加提醒"
            moreName = "点击查看更多"
         }else {
            btnName = "发送患者"
            moreName = "编辑或点击查看更多"
         }
        
        
        // 标题部分
        let dat: JSON = ["date" : dateStr, "describe" : (data["applyIllness"]?.stringValue)!, "adviceLife" : arry, "drugsAry" : drugsAry, "id": indexPath.row, "nameType": "王医生\(indexPath.row) (健康咨询):", "btnItemName": btnName, "moreBtnName" : moreName]
        
        let cell = HMProposalCell.cell(json: dat, tableView: tableView, cellForRowAt: indexPath)
        cell?.cellBlock = {
            (btn) -> () in
            if btn.titleLabel?.text == "编辑或点击查看更多" {
                 let idStr = self.dataJson[indexPath.row]["id"].stringValue
                
                NetRequestTool.shareInstance.met = .get
                NetRequestTool.request(url: "doctor/doc/prescription", parameters: ["prescId":idStr], success: { (preJson) in
                    let matter = HMRemindMatter()
                    matter.inletName = "医生出诊"
                    matter.reminderJson = preJson["data"]
                    self.pushViewController(matter)
                }, fail: { (code, msg) in
                    print("====",code)
                }, complete: {
                    
                })
                
                
       
                
            }
            
            
        }
        self.cellHeight = (cell?.cellHeight)!
        return cell!
    }
    
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//        if indexPath.section == 0 {
//            print("====添加")
//        }
    }
    
}

